<template>
	<view class="content-img">
		<eui-nav-bar ref="EuiNavBarRef" :title='title' color="#000" rightIcon="" />
		<eui-search-bar ref="knowledgeInfoSearch" v-model="searchValue" @blur="qryKnowList"  @confirm="qryKnowList" radius="100"
			placeholder="搜索标题" showFilterTitle="分类列表" showFilter >
			<template #searchFields>
				<view class="search-fields" >
					<scroll-view 
						scroll-y 
						lower-threshold='88' 
						@refresherrefresh="onRefresh" 
						@scrolltolower="templateLower"
						:refresher-enabled='true' 
						:refresher-triggered="triggered"
						:style="{height:scrollHeight}"
					>
						<view class="scroll-row flex-direction-column">
							<view class="sroll-store-list flex-row-between" 
								v-for="item in typeList" 
								@click="GetKnowInfo(item)" 
								:key="item.c_ccode"
							>
								<view class="text-ellipsis list-title" >[{{ item.c_ccode }}]{{ item.c_cname }}</view> 
								<view v-if="selectCcode==item.c_ccode" class="iconfont icon-xuanzhong" :class="[theme]"></view>
							</view>						
						</view>
					</scroll-view>
				</view>
			</template>
		</eui-search-bar>
	</view>
	<view class="main-view">
		<scroll-view scroll-y lower-threshold='88' @refresherrefresh="onRefresh" @scrolltolower="templateLower"
			:refresher-enabled='true' :refresher-triggered="triggered"
			:style="{width:scrollWidth+'px',height:scrollHeight}">									
			<Knowledge :data="KnowledgeList"/>   			
		</scroll-view>
	</view>
</template>
<script setup lang="ts">
  import dayjs from 'dayjs';
	import { ref } from 'vue';
	import { onLoad,onReady } from '@dcloudio/uni-app';
	import service from '@/common/service';
	import Enjoy from '@/common/enjoy';
	import dateRangUtil from '@/common/dateRangUtil';
	import { useMainStore } from '@/store/modules/store';
	import { useLoginStore } from '@/store/modules/useLoginStore';
    import Knowledge from './NewKnowledgeInfoDetail';

	import { storeToRefs } from 'pinia';
	import { useThemeStore } from '@/store/themeStore';
	const themeStore = useThemeStore(); // 主题
	const { theme } = storeToRefs(themeStore);
	

	const mainStore = useMainStore();
	const LoginStore = useLoginStore();	
	const scrollWidth = ref(uni.getSystemInfoSync().windowWidth - 20);
	const scrollHeight = ref(uni.getSystemInfoSync().windowHeight + 'px');
	const searchValue = ref('');
	const triggered = ref(false);
	const dataList = ref([]);
	const CurrentPage = ref(1);
	const PageCount = ref(0);
	const EuiNavBarRef = ref(null);
	const knowledgeInfoSearch = ref(null);
    const KnowledgeList = ref([])
	const typeList=ref([])
	const AllKnowledgeList = ref([])
	const selectCcode=ref('');
	const selectKnowledgeList=ref([])//查询时的
	const title=ref('');
	// 下拉刷新
	const onRefresh = ()=>{
		if (triggered.value) {
			return false;
		};
		triggered.value = true;
		CurrentPage.value = 1;
		dataList.value = [];
		//QueryNewList();
		setTimeout(() => {
			triggered.value = false;
		}, 1000)
	}
 // 获取知识中心
interface Knowledge { 
    c_number?: string | number;
    c_file_name?: string;
	c_title?:string;
    c_id?: string;
    c_guid?: string;
    c_type?: string;
    c_mk_dt?: string;
    c_mk_username?: string;
    c_cname?: string;
    c_doc_size?: string;
    c_downread_count?: string | number;
    c_docimg_url?: string;
    c_link?: string;
    [key: string]: any; 
}
interface KnowledgeInfo { 
    c_ccode?: string;
    c_cname?: string;
}
const MobileServiceAddress = service.getStorageSync("MobileServiceAddress");
const RequestHttpType = service.getStorageSync("RequestHttpType");
const baseUrl = MobileServiceAddress.indexOf('http') >= 0 ? '' : `${RequestHttpType}://${MobileServiceAddress}`;
const GetKnowLedgeNewList = (code) => {
	console.log('GetKnowLedgeNewList==code:'+code);
    service.enjoyShowLoading('正在查询...');
	let request = {
		url: LoginStore.EnjoyMain, 
		data: {
			UniqueKey: "管易通40知识中心",
			MethodName: "getChildKnowledgeList",
            ObjectData:code
		},
	};
    service.request(request, (res: any) => {
		if (res && res.data && !res.data.HasException) {
			const result=res.data.ObjectData;
			console.log('明细出参:'+JSON.stringify(result));
			if(result && result.length > 0){
		for(let i=0;i<result.length;i++){
			
		                let objectData = result[i].lstDoc;
						if (objectData && objectData.length > 0) {
							
		                const list = objectData.map((item: Knowledge) => ({
		                    ...item,
		                    c_mk_dt: dayjs(item.c_mk_dt).format('YYYY-MM-DD'),
		                    c_download_count:  item.c_type == '文件' ? item.c_download_count : item.c_read_count,
		                    c_docimg_url: item.c_type == "在线编辑" ? 'xml.png' : getDocImgType(item.c_file_name),
		                    filePath: `${LoginStore.EnjoyMain.replace('/Enjoy/Service','/File/DownLoadFile/')}${item.c_guid}`,
		                }));
						result[i].lstDoc=list;
						//KnowledgeList.value = KnowledgeList.value.concat(list);
					} 
					}
					KnowledgeList.value=result;
					}		
			
		} else {
            service.enjoyShowToast(res.data.Exception.Message )
        }
       
		service.enjoyHideLoading();
	}, () => {
		service.enjoyHideLoading();
		console.log('失败')
	});
}
const qryKnowList = () => {
	const title= searchValue.value;
	const {lstDoc} = KnowledgeList.value[0];
	if(title){
		selectKnowledgeList.value=lstDoc.filter(item => item.c_title.includes(title))
	searchValue.value='';
	if(selectKnowledgeList.value.length<=0){
		uni.showToast({
			duration: 3500,
			icon: 'none',
			title: '未查询到符合条件的信息！'
		});
	} else {
		uni.navigateTo({
			url: './SelecKonwledgeList?c_name=' + title+ '&data=' + JSON.stringify(selectKnowledgeList.value)
		});
	}
	}
	
}
const  GetKnowInfo = e => {
	selectCcode.value=e.c_ccode;
	knowledgeInfoSearch.value.closeDrawer();
	uni.navigateTo({
		url: './KnowledgeAllInfo?code=' + e.c_ccode+ '&c_name=' + e.c_cname
	});
}
const getAllKnowledgeList = () => {
    service.enjoyShowLoading('正在查询...');
	let request = {
		url: LoginStore.EnjoyMain, 
		data: {
			UniqueKey: "管易通40知识中心",
			MethodName: "getAllKnowledgeList",
            ObjectData:mainStore.loginInfo.sUser
		},
	};
    service.request(request, (res: any) => {
		if (res && res.data && !res.data.HasException) {
			
			const objectData = res.data.ObjectData;
			if (objectData && objectData.length > 0) {
				typeList.value=[];
				objectData.forEach(item => {
				          if (item.lstChild) {
				            typeList.value = typeList.value.concat(item.lstChild);
				          }
				        });
				        // 按照 c_ccode 升序排序
				        typeList.value.sort((a, b) => a.c_ccode.localeCompare(b.c_ccode));	
				AllKnowledgeList.value=objectData;
			}			
			else{
				AllKnowledgeList.value=[];
				 typeList.value=[];
			}
		} else {
            service.enjoyShowToast(res.data.Exception.Message )
        }
       
		service.enjoyHideLoading();
	}, () => {
		service.enjoyHideLoading();
		console.log('失败')
	});
}
const getDocImgType = (docName: string): string => {
  if (!docName) {
    return 'spl.png';
  }
  const fix: string = docName.substring(docName.lastIndexOf('.') + 1).toLowerCase();

  switch (fix) {
    case 'doc':
    case 'docx':
      return 'docx.png';
    case 'txt':
      return 'txt.png';
    case 'ppt':
    case 'pptx':
      return 'pptx.png';
    case 'jpg':
    case 'png':
    case 'bmp':
    case 'jpeg':
    case 'gif':
      return 'picture.png';
    case 'exe':
      return 'exe.png';
    case 'pdf':
      return 'pdf.png';
    case 'avi':
    case 'wma':
    case 'rmvb':
    case 'mp4':
    case 'mov':
    case 'mpeg':
    case 'flv':
    case 'asf':
      return 'video.png';
    case 'html':
    case 'xml':
      return 'xml.png';
    case 'xls':
    case 'xlsx':
    case 'xlsm':
      return 'xlsx.png';
    default:
      return 'spl.png';
  }
};
	// 加载更多
	const templateLower = ()=>{
		if (CurrentPage.value < PageCount.value) {
			CurrentPage.value = CurrentPage.value + 1;
			//QueryNewList();
		}
	}
	onReady(()=>{
		uni.getSystemInfo({
			success: function(res) {
				const userInfoPage = uni.createSelectorQuery().select(".content-img");
				userInfoPage.boundingClientRect(function(data) {
					scrollHeight.value = (res.windowHeight - data.height - 20)+'px';
				}).exec()
			}
		});
	})
	onLoad((e)=>{
		title.value=e.c_name;
		selectCcode.value=e.code;
        GetKnowLedgeNewList(e.code);
		getAllKnowledgeList();
	})
</script>

<style lang="scss" scoped>
	@import '@/main.scss';

	.content-img {
		background-color: #FFFFFF;
		background-repeat: no-repeat;
		width: 100%;
	}
	.store-checked {
		background-color: rgb(23, 226, 77) !important;
	}
	.sroll-store-list {
		height: 88rpx;
		border-bottom: solid 1px rgba(238, 238, 238, 1);
	}
	.main-view {
		flex: 1;
		flex-direction: column;
		padding: 20rpx;
		background-color: #f2f2f2;
	}

	.approve-list {
		padding: 28rpx 28rpx 28rpx 28rpx;
		border-radius: 20rpx;
		background-color: #fff;
	}

	.flex {
		display: flex;
	}

	.flex-1 {
		flex: 1;
	}

	.flex-direction-column {
		flex-direction: column !important;
	}

	.font-size-20 {
		font-size: 20rpx;
	}

	.font-size-24 {
		font-size: 24rpx;
	}

	.font-size-28 {
		font-size: 28rpx;
	}

	.font-size-30 {
		font-size: 30rpx;
	}

	.font-weight-bold {
		font-weight: bold;
	}

	.color-888 {
		color: #888;
	}

	.margin-bottom-20 {
		margin-bottom: 20rpx;
	}

	.margin-top-12 {
		margin-top: 12rpx;
	}

	.padding-left-20 {
		padding-left: 20rpx;
	}

	.ellipsis-1 {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.news-radius {
		width: 8px;
		height: 8px;
		background-color: rgba(255, 64, 0, 1);
		position: absolute;
		top: -3px;
		right: -3px;
		border-radius: 50%;
	}
	.scroll-row {
		width: 100%;
		padding: 0 28rpx;
		box-sizing: border-box;
		.list-title {
			flex: 1;
			width: 0;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 14px;
			color: #000000;
		}
	}
	.icon-xuanzhong {
		font-size: 16px;
		color: var(--theme-color);
	}
</style>